package com.example.hostsys.service;

import com.example.hostsys.dao.HostDao;
import com.example.hostsys.dao.StuDao;
import com.example.hostsys.dao.UserDao;
import com.example.hostsys.entity.HostMan;
import com.example.hostsys.entity.Student;
import com.example.hostsys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    HostDao hostDao;
    @Autowired
    StuDao stuDao;

    public void newHost(HostMan hostMan,User user){
        hostMan.setUser(user);
        hostMan.setId(user.getId());
        hostDao.save(hostMan);
        user.setRole(user.getRole()+",ROLE_HOST");
        userDao.save(user);
    }

    public void newStu(Student student, User user){
        student.setUser(user);
        student.setId(user.getId());
        stuDao.save(student);
        user.setRole(user.getRole()+",ROLE_Stu");
        userDao.save(user);
    }

    public void newUser(User user){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));
        user.setRole("ROLE_USER");
        userDao.save(user);
    }
    public boolean isExist(String username) {
        return userDao.findByUsername(username)!=null;
    }
    public User findUser(String username) {
        return userDao.findByUsername(username);
    }
}
